package cn.chenwx.bbsforum.controller;

import cn.chenwx.bbsforum.entity.User;
import cn.chenwx.bbsforum.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    UserService userService;


    @GetMapping("/toLogin")
    public String getLogin(){
        return "admin/login";
    }
    @GetMapping("/user/login")
    public String userLogin(){
        return "login";
    }
    @PostMapping("/user/home")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session){
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean tureUser =false;
        User user=userService.findUserByName(username);

        if (user!=null){
            tureUser=bCryptPasswordEncoder.matches(password,user.getPassword());
            if (tureUser)
            session.setAttribute("user",user);
            session.setAttribute("username",user.getUsername());
            session.setAttribute("role",user.getRole());
            return "index";
        }else {
            session.setAttribute("errorMsg","用户名或密码错误！");
            return "login";
        }


    }





}
